package com.soujiayi.coupon;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Environment;

public class ImageDownTool {
	private static final String WHOLESALE_CONV = ".cache";
	private String cachdir = "com.lesou.rongyi/caches";
	private boolean cache = true;
	private Activity mActivity;
	public ImageDownTool(Activity activity) {
		this.mActivity = activity;
	}

	public void downloadBitmap(String path, int w, int h, int position) {
		if (path == null) {
			return;
		}
		BitmapDownloaderTask task = new BitmapDownloaderTask();
		task.execute(path, w, h, position);
	}

	private class BitmapDownloaderTask extends AsyncTask<Object, Void, Bitmap> {
		private String imgUrl, replaceUrl, url;
		private boolean fromFile; // 判断图片是否从本地读取的
		private boolean fromMemory; // 判断图片是否从内存读取的
		private int position;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Bitmap doInBackground(Object... params) { // 实际的下载线程，内部其实是concurrent线程，所以不会阻塞
			position = (Integer) params[3];
			return downloadBitmap((String) params[0], (Integer) params[1],
					(Integer) params[2], (Integer) params[3]);

		}

		private Bitmap downloadBitmap(String path, int w, int h, int position) {
			url = path;
			// 本地缓存地址
			replaceUrl = convertUrlToFileName(path);
			// 图片下载地址
			imgUrl = path.substring(path.indexOf("|") + 1, path.length());
			if (cache) {

				// 从内存缓存获得图片
				Bitmap bm = BitmapCache.getInstance().getBitmap(path);
				if (bm != null && !bm.isRecycled()) {
					fromMemory = true;
					System.out.println(" - - - 图片从内存缓存读取成功 - - - ");
					return bm;
				}
				// 从本地缓存获得图片
//				if (MyApp.HAS_CACHE) {
//					File file = new File(getDirectory());
//					if (!file.isDirectory()) {
//						file.mkdirs();
//					}
//					file = new File(getDirectory() + "/" + replaceUrl);
//					if (file.isFile()) {
//						Bitmap bitmap = ImageUtil.pathToBitmap(getDirectory()
//								+ "/" + replaceUrl);
//						fromFile = true;
//						System.out.println(" - - - 图片从本地缓存读取成功 - - - ");
//						return bitmap;
//					}
//				}
			}
			try {
				byte[] data = getByteArray(imgUrl);
				if (data != null) {
					System.out.println(" - - - 图片从网络下载 - - - ");
					return zoomBitmapOptions(data, w, h);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap bm) { // 下载完后执行的
			if (isCancelled()) {
				bm = null;
			}
			if (bm == null || bm.isRecycled()) {
				return;
			}
			if (bm != null) {
				if (cache) {
					if (!fromMemory) {
						BitmapCache.getInstance().addCacheBitmap(bm, url);
						System.out.println(" - - - 图片存入内存缓存成功 - - - ");
					}
					if (!fromFile) {
						FileUtil.savePNG_After(bm, getDirectory(), replaceUrl);
						System.out.println(" - - - 图片存入本地缓存成功 - - - ");
					}
				}
			}
			onGetBitmapListener.dealBitmap(bm, position);
		}
	}

	private OnGetBitmapListener onGetBitmapListener;

	public void setOnGetBitmapListener(OnGetBitmapListener onGetBitmapListener) {
		this.onGetBitmapListener = onGetBitmapListener;
	}

	public interface OnGetBitmapListener {
		void dealBitmap(Bitmap bm, int position);
	}

	/** 将url转成文件名 **/
	public String convertUrlToFileName(String url) {
		if (url == null) {
			return null;
		}
		// String[] strs = url.split("/");
		// return strs[strs.length - 1] + WHOLESALE_CONV;
		char r[] = { ':', '/', '\\', '?', '*', '>', '<', '|', '"' };
		for (int i = 0; i < r.length; i++) {
			url = url.replace(r[i], '!');
		}
		return url + WHOLESALE_CONV;
	}

	/** 获得缓存目录 **/
	public String getDirectory() {
		if (getSDPath().equals("")) {
			return "";
		}
		String dir = getSDPath() + "/" + cachdir;
		return dir;
	}

	/**** 取SD卡路径不带/ ****/
	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		// 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();
			// 获取跟目录
		}
		if (sdDir != null) {
			return sdDir.toString();
		} else {
			return "";
		}
	}

	public static byte[] getByteArray(String path) throws IOException {
		byte[] data = doGet(path);
		if (data != null) {
			return data;
		} else {
			// System.out.println("--- 第二次get请求 ---");
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			data = doGet(path);
			if (data != null) {
				// System.out.println("--- 第二次get请求成功 ---");
				return data;
			} else {
				// System.out.println("--- 第三次get请求 ---");
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				data = doGet(path);
				if (data != null) {
					// System.out.println("--- 第三次get请求成功 ---");
					return data;
				}
			}
		}
		return data;
	}

	private static byte[] doGet(String path) throws IOException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");

		if (conn.getResponseCode() == 200) {
			InputStream is = conn.getInputStream();
			byte[] data = readStream(is);
			return data;
		}
		return null;
	}

	public static byte[] readStream(InputStream is) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while (-1 != (len = is.read(buffer))) {
			bos.write(buffer, 0, len);
		}
		is.close();
		return bos.toByteArray();
	}

	public static Bitmap zoomBitmapOptions(byte[] data, int w, int h) {
		if (w == 0) {
			Bitmap b = bytesToBitmap(data);
			if (b != null) {
				return zoomBitmap(b, w, h);
			} else {
				return null;
			}
		}
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		// 获取这个图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
				opts); // 此时返回bm为空

		int outW = opts.outWidth;
		int outH = opts.outHeight;

		opts.inJustDecodeBounds = false;

		opts.inSampleSize = 1;
		// 计算缩放比
		int size = (int) (outW / w);
		if (size <= 0) {
			size = 1;
		}
		opts.inSampleSize = size; //
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
		bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);

		if (bitmap != null) {
			return zoomBitmap(bitmap, w, h);
		}
		return null;
	}

	// 将byte[]转化我Bitmap
	public static Bitmap bytesToBitmap(byte[] data) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return bitmap;
	}

	// 放大缩小图片
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		if (h == 0) {
			return zoomScaleBitmap(bitmap, w);
		}
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		if (w == width && h == height) {
			return bitmap;
		}

		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		bitmap.recycle();
		return newbmp;
	}

	// 放大缩小图片,按比例
	public static Bitmap zoomScaleBitmap(Bitmap bitmap, int w) {
		int width = bitmap.getWidth();
		if (width == w || w == 0) {
			return bitmap;
		}
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		int h = height * w / width;
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);

		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		bitmap.recycle();
		return newbmp;
	}

	public boolean isCache() {
		return cache;
	}

	public void setCache(boolean cache) {
		this.cache = cache;
	}
}
